const app = getApp();
import {
  getSort,
  get
} from '../../utils/db'
Page({
  data: {
    id: 0,
    userInfo: {},
    isLogin: false, //是否登录。 false 未登录  true，已经登录
    recipes: [], //菜单列表
    types: [], //分类列表
    lists: [], //关注
  },
  //删除
  _delStyle() {
    wx.showModal({
      title: "删除提示",
      content: "确定要删除么？",
    })
  },
  //菜单切换页面
  async menuClick(e) {
    var id = e.currentTarget.id;
    this.setData({
      id
    })
    if (id == 1) {
      var result = await get("class")
      this.setData({
        types: result.data
      })
    }
  },
  //分类
  classClick(e) {
    var _id = e.currentTarget.id;
    wx.navigateTo({
      url: '../list/list?id=' + _id,
    })
  },
  //菜单添加
  jia() {
    wx.navigateTo({
      url: '../pbrecipe/pbrecipe',
    })
  },
  //分类添加
  add() {
    wx.navigateTo({
      url: '../category/category',
    })
  },
  //菜单列表，点击跳转
  detail(e) {
    var id = e.currentTarget.id;
    wx.navigateTo({
      url: '../detail/detail?id=' + id,
    })
  },
  async onShow() {
    //获取登录信息
    let userInfo = app.globalData.userInfo;
    if (userInfo == null) {
      this.data.isLogin = false;
    } else {
      this.data.isLogin = true;
    }
    //菜单列表
    var openid = wx.getStorageSync('openid'); //通过缓存获取openid
    var reslut = await getSort("menu", {
      _openid: openid
    })

    //关注
    var openid = wx.getStorageSync('openid');
    //获取你关注数据
    var result = await get("likes", {
      _openid: openid
    }).catch(err => console.log(err))
    //获取menuId把他们放到一个数组中
    var arr = result.data.map(item => {
      return item.menuId
    })
    //根据arr中的menuId  获取到menu菜单里的数据
    var result = await getSort("menu", {
      _id: wx.cloud.database().command.in(arr)
    })
    //星星
    var lists = result.data;
    lists.forEach(item => {
      if (item.views == 0) {
        item.star = 0
      } else if (item.views > 0 && item.views <= 10) {
        item.star = 1;
      } else if (item.views > 10 && item.views <= 20) {
        item.star = 2;
      } else if (item.views > 20 && item.views <= 30) {
        item.star = 3;
      } else if (item.views > 30 && item.views <= 40) {
        item.star = 4;
      } else {
        item.star = 5;
      }
    })
    //渲染到页面
    this.setData({
      lists, //关注列表
      userInfo, //用户信息
      recipes: reslut.data, //分类
      isLogin: this.data.isLogin //判断是否登录
    })
  },
  //关注列表，点击跳转到详情页
  toDetail(e) {
    var id = e.currentTarget.id;
    wx.navigateTo({
      url: '../detail/detail?id=' + id,
    })
  },

  //点击登录
  userInfo(e) {
    if (e.detail.userInfo !== undefined) {
      this.setData({
        userInfo: e.detail.userInfo,
        isLogin: true
      })
    }
  }

})